$(document).ready(function () {
    $(".btn").bind("click", function () {
        //1.获取用户输入的内容和配置选项的参数
        var content = $(".text").val();
        var spd = $("#spd_show").text();
        var pit = $("#pit_show").text();
        var vol = $("#vol_show").text();
        var v = document.getElementById("ptp").value;
        var v2 = document.getElementById("ptp2").value;
        if (v != 0 || v != 1 || v != 3 || v != 4) {
            v = v2
        }
        console.log(spd)
        console.log(pit)
        console.log(vol)
        //
        var config = {
            url: "baidu_ai?model=speech",
            method: "post",
            dataType: "json",
            data: {
                type: "audio_merge",
                content: content,
                spd: spd,
                pit: pit,
                vol: vol,
                per: v,
            },
            success: function (resp) {
                console.log(resp)
                var audio = $("#audio")[0];
                audio.setAttribute("src", "data:audio/mp3;base64," + resp.data)
                audio.load()
                audio.play()
                base64toBlob(resp.data, "Unicode")
                console.log(base64toBlob(resp.data))
            },
            error: function (resp) {
                console.log(resp)
            }
        }
        //
        $.ajax(config);

    })


});


function base64toBlob(base64, type) {
    // 将base64转为Unicode规则编码
    let bstr = atob(base64, type),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n) // 转换编码后才可以使用charCodeAt 找到Unicode编码
    }
    return new Blob([u8arr], {
        type,
    })
}

function dataURItoBlob(dataURI) {
    var base64Arr = dataURI.split(",");
    var imgtype = "";
    var base64String = "";
    if (base64Arr.length > 1) {
        //如果是图片base64，去掉头信息
        base64String = base64Arr[1];
        imgtype = base64Arr[0].substring(
            base64Arr[0].indexOf(":") + 1,
            base64Arr[0].indexOf(";")
        );
    }
    // 将base64解码
    var bytes = atob(base64String);
    //var bytes = base64;
    var bytesCode = new ArrayBuffer(bytes.length);
    // 转换为类型化数组
    var byteArray = new Uint8Array(bytesCode);

    // 将base64转换为ascii码
    for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
    }

    // 生成Blob对象（文件对象）
    return new Blob([bytesCode], {type: imgtype});
}

